/* eslint-disable no-undef */
// 选择题

const question = require('../../model/question/question');
const { getTime } = require('../../utils/gettime');
const { Op } = require('sequelize');

const { isJson } = require('../../rules/verification');

let attributes = [
    'id',
    'title',
    'options',
    'answer',
    'creator',
    'createdate',
    'updator',
    'updated',
    'chapter_id',
    'difficulty',
    'usage',
    'type_id',
    'analysis',
    'catalouge_id'
];

// 根据id获取题数据
exports.getById = async ({ id }) => {
    try {
        let res = await question.findOne({ attributes, where: { id } });
        if (res.options) {
            res.options = JSON.parse(res.options);
            res.answer = JSON.parse(res.answer);
        }
        if (res) return { msg: '获取成功', code: '200', data: res };
        return { msg: '获取失败', code: '400' };
    } catch (err) { return { msg: '获取试题失败', code: '400', err }; }
};
// 获取题列表
exports.getList = async ({ pageNum, pageSize, type_id, title }) => {
    console.log(pageNum, pageSize);
    try {
        // return title

        let where = {};
        if (type_id) {
            where.type_id = type_id;
        }
        if (title) {
            where.title = {
                [Op.like]: `%${title}%`
            };
        }
        let res = await question.findAndCountAll({
            offset: pageNum * pageSize - pageSize,
            limit: pageSize,
            attributes,
            where,
            order: [
                ['id', 'DESC']  // 降序
                // ['id'] 升序
            ]
        });
        if (res) {
            res.rows.forEach(item => {
                // let arr = item.title.split(' ')
                // let arrStr = ''
                // arr.forEach(item => {
                //     if(item == "$lt") item = "<"
                //     if(item == "$gt") item = ">"
                //     arrStr += item
                // })
                // item.title = arrStr

                if (item.type_id == 1) {
                    item.options = JSON.parse(item.options);
                    item.answer = JSON.parse(item.answer);
                } else if (type_id == 2) {
                    item.answer = JSON.parse(item.answer);
                }
            });
            return { msg: '获取成功', code: '200', data: res };
        } else {
            return { msg: '获取失败1', code: '400' };
        }
    } catch (err) { return { msg: '获取试题失败2', code: '400', err }; }
};

// 添加试题
// eslint-disable-next-line no-undef
exports.create = async ({ title, chapter_id, options, answer, creator, difficulty, type_id, analysis, catalouge_id }) => {
    try {
        let arr = title.split('');
        let arrStr = '';
        arr.forEach(item => {
            if (item == '<') item = ' 《 ';
            if (item == '>') item = ' 》 ';
            arrStr += item;
        });
        title = arrStr;
        console.log(arrStr);
        let isCreate = await question.findOne({ where: { title } });
        if (isCreate) return { msg: '重复的试题题干', code: '400' };
        let newData = {};
        if (!creator) newData.creator = creator;
        newData.difficulty = difficulty;
        newData.title = title;
        newData.chapter_id = chapter_id;
        newData.type_id = type_id;
        newData.answer = answer;
        newData.analysis = analysis;
        newData.updated = getTime();
        newData.catalouge_id = catalouge_id;
        if (type_id == 1) {
            let checkoptions = isJson(options, '选项');
            if (checkoptions.code != '200') return checkoptions;
            let checkanswer = isJson(answer, '选择题答案');
            if (checkanswer.code != '200') return checkanswer;
            console.log(answer);
            answer = JSON.stringify(answer);
            newData.answer = answer.toUpperCase();

            if (typeof options == 'string') {
                options = JSON.parse(options);
            }
            if (options.length <= 1) return { msg: '添加失败 最少包含两个选项', code: '400' };
            // 选项字母转换成大写
            options.forEach(item => {
                item.sign = item.sign.toUpperCase();
            });
            options = JSON.stringify(options);
            newData.options = options;
        } else if (type_id == 3) {
            answer = JSON.parse(answer);
            if (answer != true) {
                if (answer != false) return { msg: '答案应是 boolean 类型', code: '400' };
            }
        } else if (type_id == 2) {
            let checkanswer = isJson(answer, '填空题答案');
            if (checkanswer.code != '200') return checkanswer;
        }
        newData.createdate = getTime();
        let res = await question.create(newData);
        if (res) return { msg: '添加成功', code: '200' };
        return { msg: '添加失败', code: '400' };
    } catch (err) { console.log(err); return { msg: '添加题失败', code: '400', err }; }
};

// 编辑题
exports.edit = async ({ id, title, type_id, chapter_id, options, answer, updator, difficulty, analysis, catalouge_id }) => {
    // try {
        let isTitle = await question.findOne({ where: { id }, attributes: ['id', 'type_id', 'title'] });
        let newData = {};
        // 每道题只能出现一次
        if (title) {
            let isedit = await question.findOne({ where: { title }, attributes: ['id'] });
        if (isedit) {
            if (isedit.id != id) return { msg: '编辑失败 重复的题目', code: '400' };
        }
    }
    if (title) newData.analysis = analysis;
    if (title) newData.title = title;
    if (chapter_id) newData.chapter_id = chapter_id;
    if (isTitle.type_id == '1') {
        if (options) {
            let checkOpt = isJson(options, '选项');
            if (checkOpt.code != '200') return checkOpt;
            if (options.length <= 1) return { msg: '添加失败 最少包含两个选项', code: '400' };
            newData.options = JSON.stringify(options);
            console.log(options);
        }
        // 答案选项转换成大写
        if (answer) {
            let checkAnswer = isJson(answer, '选择题答案');
            if (checkAnswer.code != '200') return checkAnswer;
            answer = JSON.stringify(answer);
            console.log(answer,'=================');
            console.log(answer,'=================');
            console.log(answer,'=================');
            console.log(answer,'=================');
        }
    } else if (isTitle.type_id == '3') {
        if (answer) {
            let checkAns = isJson(answer, '判断题答案');
            if (checkAns.code != '200') return checkAns;
            answer = JSON.parse(answer);
            if (answer != true) {
                if (answer != false) return { msg: '答案应是 boolean 类型', code: '400' };
                newData.answer = answer;
            }
        }
    } else if (type_id == 2) {
        let checkanswer = isJson(answer, '填空题答案');
        if (checkanswer.code != '200') return checkanswer;
    }
    if (answer) newData.answer = answer;
    if (updator) newData.updator = updator;
    newData.difficulty = difficulty;
    newData.catalouge_id = catalouge_id;
    newData.updated = getTime();
    // return newData
    let res = await question.update(newData, { where: { id } });
    if (res) return { msg: '编辑成功', code: '200' };
    return { msg: '编辑失败', code: '400' };
    // } catch (err) { return { msg: "编辑试题失败", code: "400", err } }
};

// 删除题
exports.remove = async ({ id }) => {
    // try {
        let res = await question.destroy({ where: { id } });
        if (res) return { msg: '删除试题成功', code: '200' };
        return { msg: '删除试题失败', code: '400' };
    // } catch (err) { return { msg: '删除试题失败', code: '400', err }; }
};